package com.dinggao.crossgo.module.user;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.os.Bundle;

import com.dinggao.crossgo.R;
import com.dinggao.crossgo.core.base.BaseActivity;
import com.dinggao.crossgo.core.constant.CommonConstant;
import com.dinggao.crossgo.core.manage.ApiManager;
import com.dinggao.crossgo.core.paser.FastJsonUtils;
import com.dinggao.crossgo.core.util.LogUtils;
import com.dinggao.crossgo.core.util.NetUtils;
import com.dinggao.crossgo.core.util.SharedPreferencesUtil;
import com.dinggao.crossgo.core.util.ToastUtil;
import com.dinggao.crossgo.module.roadbook.activity.RoadBookPublishMainActivity;
import com.dinggao.crossgo.module.user.login.CheckTokenBean;
import com.dinggao.crossgo.module.user.login.LoginActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.reactivestreams.Subscription;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class SplashActivity extends BaseActivity {

    public static final String TAG = "SplashActivity";
    private boolean Flag = false;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_splash;
    }

    @Override
    protected void onInitialization(Bundle bundle) {

        getPermission();

    }


    private void getPermission() {
        RxPermissions rxPermissions = new RxPermissions(SplashActivity.this);


        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE ,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE)
             .subscribe(new Observer<Boolean>() {
                 @Override
                 public void onSubscribe(Disposable d) {

                 }

                 @Override
                 public void onNext(Boolean aBoolean) {

                     if (aBoolean){
                         startCountDown();
                     }else {
                         AlertDialog mPermissionDialog = new AlertDialog.Builder(SplashActivity.this)
                                 .setTitle("友情提醒")
                                 .setMessage("亲，我需要权限，请赐给我吧！")
                                 .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                     @Override
                                     public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                         Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                         Uri uri = Uri.fromParts("package", getPackageName(), null);
                                         intent.setData(uri);
                                         startActivity(intent);
                                     }
                                 })
                                 .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                     @Override
                                     public void onClick(DialogInterface dialog, int which) {

                                         dialog.cancel();
                                     }
                                 })
                                 .create();
                         mPermissionDialog.show();

                     }
                 }

                 @Override
                 public void onError(Throwable e) {

                 }

                 @Override
                 public void onComplete() {

                 }
             });

    }


    private void startCountDown() {

        final String accessToken = SharedPreferencesUtil.getSharedPreferencesString(SplashActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN);
        final int count = 2;//倒计时3秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (accessToken != null && accessToken.length() > 0) {
                            if (NetUtils.isNetworkAvailable(SplashActivity.this)){
                                checkAccessToken(accessToken);
                            }else {
                                ToastUtil.showLong(SplashActivity.this,"当前没有网络连接");
                            }

                        }
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {


            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                if (Flag) {
                    // 校验通过跳转到首页
                    Intent intent = new Intent();
                    intent.setClass(SplashActivity.this, RoadBookPublishMainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(SplashActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }


    /**
     * 检查Token
     *
     * @param accessToken
     */
    private boolean checkAccessToken(String accessToken) {

        //7cd23670-a003-42ea-9236-70a00332ea99
        LogUtils.e(TAG, accessToken);
        OkGo.<String>get(ApiManager.CHECK_TOKEN)
                .params("accessToken", accessToken)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        CheckTokenBean bean = FastJsonUtils.getObject(response.body(), CheckTokenBean.class);
                        LogUtils.e(TAG, "onSuccess: " + bean.getCode() + "");
                        if (bean.getCode() == 0) {
                            Flag = true;
                        } else {
                            Flag = false;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                        Flag = false;
                    }
                });

        return Flag;
    }


}
